import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

class Solution {
    public List<List<Integer>> fourSum(int[] nums, int target) {
        Arrays.sort(nums);
        List<List<Integer>> list = new ArrayList<>();
        for (int i = 0; i < nums.length; ) {//
            for (int j = i+1; j < nums.length; ) {
                int left = j+1;
                int right = nums.length-1;
                while (left < right) {
                    long aim = (long)nums[left]+nums[right]+nums[j];
                    if (aim == target-nums[i]) {
                        List<Integer> list1 = new ArrayList<>();
                        list1.add(nums[i]);
                        list1.add(nums[j]);
                        list1.add(nums[left]);
                        list1.add(nums[right]);
                        list.add(list1);
                        left++;
                        right--;
                        while (left < right && nums[left] == nums[left-1]) left++;
                        while (left < right && nums[right] == nums[right+1]) right--;
                    }else if (aim > target-nums[i]) {
                        right--;
                    }else {
                        left++;
                    }
                }
                j++;
                while (j < nums.length && nums[j] == nums[j-1]) j++;
            }
            i++;
            while (i < nums.length && nums[i] == nums[i-1]) i++;
        }
        return list;
    }
}